package com.credithc.signature.facade.controller.fadada;

import com.alibaba.fastjson.JSON;
import com.credithc.baseserv.core.codes.CoreCodes;
import com.credithc.baseserv.core.message.Message;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.signature.common.mapper.SealChannelMapper;
import com.credithc.signature.common.po.SignatureLog;
import com.credithc.signature.common.po.SignatureLogExt;
import com.credithc.signature.common.ro.GetExtSignPageRo;
import com.credithc.signature.common.ro.core.CoreRequet;
import com.credithc.signature.common.ro.facade.FddAuthReq;
import com.credithc.signature.common.ro.facade.FddSignReq;
import com.credithc.signature.common.service.ChannelService;
import com.credithc.signature.common.service.LogAndExtService;
import com.credithc.signature.common.service.TemplateService;
import com.credithc.signature.common.utils.UUIDUtil;
import com.credithc.signature.facade.client.FadadaRemoteClient;
import com.credithc.signature.facade.facadeenum.ResponseEnum;
import com.credithc.signature.facade.ro.RestSignatureReq;
import com.credithc.signature.facade.service.FddParamVerifyService;
import com.credithc.signature.facade.service.ParamVerifyService;
import com.credithc.signature.facade.util.FileUtil;
import com.credithc.signature.facade.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @desc: 法大大签章接口<br />
 * @author: Jingbo Hu<br/>
 * @time：2020年07⽉15⽇<br/>
 * @version：v1.0.0<br>
 */
@RestController
@RequestMapping("/api/signaturefacade/v1")
@Slf4j
public class FddSignController {

    @Autowired
    MessageFactory messageFactory;

    @Autowired
    FadadaRemoteClient remote;

    @Autowired
    FddParamVerifyService verifyService;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private SealChannelMapper sealChannelMapper;

    @Autowired
    private LogAndExtService logAndExtService;

    @Autowired
    ParamVerifyService paramVerifyService;


    /**
     * 申请证书: 1: 编号证书 2:实名证书
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/applyCert")
    public Message applyCert(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams2(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.applyCert(req);
    }


    @ResponseBody
    @PostMapping("/sign/signUrl")
    public Message getSignUrl(@RequestHeader String encryptKey, @RequestBody @Valid GetExtSignPageRo req) {
        // 校验参数
        Message message = verifyService.verifyParams14(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.getSignUrl(req);
    }

    @ResponseBody
    @PostMapping("/sign/signUrl/batch")
    public Message getBatchSignUrl(@RequestHeader String encryptKey, @RequestBody @Valid GetExtSignPageRo req) {
        // 校验参数
        Message message = verifyService.verifyParams15(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.getBatchSignUrl(verifyService.bulidBatchSignUrl(req));
    }


    /**
     * UUID下载图片
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/download")
    public Message download(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams3(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.download(req);
    }

    /**
     * 获取用户印章
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/querySignatureInfo")
    public Message querySignature(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams10(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.querySignatureInfo(req);
    }

    /**
     * 合同上传
     *
     * @param request
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/uploadContract")
    public Message uploadContract(HttpServletRequest request) {
        String contractId = request.getParameter("contractId");
        String docTitle = request.getParameter("docTitle");
        String docType = request.getParameter("docType");
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile multipartFile = null;
        if (files.size() > 0) {
            multipartFile = files.get(0);
        } else {
            return messageFactory.getInstance(CoreCodes.CORE_SYS_ERROR);
        }
        File file = FileUtil.multipartFileToFile(multipartFile);
        FddAuthReq req = new FddAuthReq();
        req.setFile(file);
        req.setContractId(contractId);
        req.setDocTitle(docTitle);
        req.setDocType(docType);
        // 校验参数
        Message message = verifyService.verifyParams4(req);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.uploadContract(req);
    }

    /**
     * 合同下载
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/downloadContract")
    public Message downloadContract(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams5(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.downloadContract(req);
    }

    /**
     * 合同归档
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/contractOver")
    public Message contractOver(@RequestHeader String encryptKey, @RequestBody @Valid FddAuthReq req) {
        // 校验参数
        Message message = verifyService.verifyParams7(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.contractOver(req);
    }

    /**
     * 合同续签
     *
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/sign/contractRenewal")
    public Message contractRenewal(@RequestHeader String encryptKey, @RequestBody @Valid FddSignReq req) {
        // 校验参数
        Message message = verifyService.verifyParams12(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.contractRenewal(req);
    }

    /**
     * 获取合同状态
     *
     * @param encryptKey
     * @param req
     * @return
     */
    @ResponseBody
    @PostMapping("/contract/status")
    public Message getContractStatus(@RequestHeader String encryptKey, @RequestBody @Valid FddSignReq req) {
        Message message = verifyService.verifyParams13(req, encryptKey);
        int code = message.getCode();
        if (0 != code) {
            return message;
        }
        return remote.getContractStatus(req);
    }

    /**
     * 手动签章：生成合同+上传+返回合同号
     *
     * @param encryptKey
     * @param restSignatureReq
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("synchronous/signature")
    public Message signature(@RequestHeader String encryptKey, @RequestBody @Valid RestSignatureReq restSignatureReq) throws Exception {

        final String signatureSN = UUIDUtil.getUUID();

        // 1、校验渠道
        if (!paramVerifyService.existChannel(encryptKey, restSignatureReq)) {
            return messageFactory.getInstance(100, ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_CHANNEL.getCode()));
        }

        // 2、校验模板
        if (!paramVerifyService.existTemplate(restSignatureReq)) {
            return messageFactory.getInstance(100, ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_TEMPLATE.getCode()));
        }

        // 3、校验公章
        if (!paramVerifyService.existSeal(restSignatureReq)) {
            return messageFactory.getInstance(100, ResponseUtil.getResponseMessage(ResponseEnum.ILLEGAL_OFFICIAL_SEAL.getCode()));
        }

        /**
         * 保存数据
         */
        Date date = new Date();
        SignatureLogExt signatureLogExt = new SignatureLogExt(JSON.toJSONString(restSignatureReq.getRequestData()), date, date);
        SignatureLog signatureLog = new SignatureLog(signatureSN, restSignatureReq.getTemplateNo(), restSignatureReq.getChannelNo(), 0, restSignatureReq.getNeedSign(), restSignatureReq.getCallBackUrl(),
                0, 0, date, date);
        logAndExtService.insertSelective(signatureLogExt, signatureLog);

        // 发送请求
        CoreRequet coreRequet = new CoreRequet(signatureSN, restSignatureReq.getTemplateNo(), restSignatureReq.getChannelNo(), restSignatureReq.getNeedSign(), restSignatureReq.getCallBackUrl(), JSON.toJSONString(restSignatureReq.getRequestData()), true);
        return remote.synchronouSign(coreRequet);
    }


}
